/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * SalarioPanel.java
 *
 * Created on 05/12/2011, 04:18:19
 */
package proj5labbd.graphics.consultas;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.DefaultTableModel;
import proj5labbd.DBInterface;
import proj5labbd.graphics.abstractOpGraphics.OperationPanel;

/*
 * Panel utilizado para consultas pré definidas pelo desenvolvedor
 * no caso, apresenta informações sobre os funcionários de um departamento tal como o seu salário
 */
public class SalarioPanel extends OperationPanel {

    /** Creates new form SalarioPanel */
    public SalarioPanel(SalarioFrame frame, DBInterface dbInterface) {
        super(frame,dbInterface);
        try {
            initComponents();
            jbtOk.addActionListener(new SalarioAction());
            Statement stmt = dbInterface.getConn().createStatement();
            stmt.executeQuery(query);
        } catch (SQLException ex) {
            Logger.getLogger(SalarioPanel.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
     
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jlbpt1 = new javax.swing.JLabel();
        jlbpt2 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtbSalario = new javax.swing.JTable();
        jbtOk = new javax.swing.JButton();

        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentShown(java.awt.event.ComponentEvent evt) {
                formComponentShown(evt);
            }
        });

        jlbpt1.setText("Média salarial por departamento,");

        jlbpt2.setText("para departamentos com mais de 1 funcionário.");

        jtbSalario.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jScrollPane1.setViewportView(jtbSalario);

        jbtOk.setText("Ok");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jlbpt2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jlbpt1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap(36, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jbtOk, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 375, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jlbpt1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jlbpt2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 230, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jbtOk))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void formComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentShown
        // TODO add your handling code here:
        try {
            // TODO add your handling code here:
            setupTable();
        } catch (SQLException ex) {
            Logger.getLogger(SalarioPanel.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_formComponentShown

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton jbtOk;
    private javax.swing.JLabel jlbpt1;
    private javax.swing.JLabel jlbpt2;
    private javax.swing.JTable jtbSalario;
    // End of variables declaration//GEN-END:variables

    //configura a(s) tabela(s) a partir de informações resgatadas na base de dados
    private void setupTable() throws SQLException {
        
        Statement stmt = dbInterface.getConn().createStatement();
        ResultSet rs = stmt.executeQuery("SELECT * FROM media");
        
        String sArray[][] = dbInterface.rsToStringArray(rs);

        DefaultTableModel model = new DefaultTableModel(sArray,
                new String[]{"Departamento","Qtde. de Funcionários","Média Salarial"}
                );
        jtbSalario.setModel(model);
    }
    
    //ouvinte das ações do botão ok
    class SalarioAction implements ActionListener {

        public void actionPerformed(ActionEvent e) {

            if (e.getSource() == jbtOk) {
                frame.dispose();
                
            }

        }


    }
    //script SQL utilizado na consulta
    private final String query = "CREATE OR REPLACE VIEW media AS "+
                                    "SELECT departamento.nomeDe AS Departamento, COUNT(funcionario.idFu) AS Quantidade_de_funcionarios, AVG(funcionario.salarioFu) AS Media_salarial "+
                                    "FROM departamento JOIN trabalho JOIN funcionario "+
                                    "ON trabalho.idFu = funcionario.idFu "+
                                    "ON departamento.idDe = trabalho.idDe "+
                                    "GROUP BY departamento.nomeDe "+
                                    "HAVING COUNT(funcionario.idFu) > 1";
                                 

}
